package com.Xht.www.servlet;

//后端接收商家同意入住申请的请求

import com.Xht.www.dao.UserHistoryOrdersDAO;
import com.Xht.www.po.UserHistoryOrdersPO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.List;

@WebServlet("/ApproveCheckInServlet")
public class ApproveCheckInServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");
        UserHistoryOrdersDAO dao = new UserHistoryOrdersDAO();

        if ("list".equals(action)) {
            // 列出申请中的订单
            String merchantName = request.getParameter("merchantName");
            List<UserHistoryOrdersPO> orders = dao.getAllOrdersByMerchantNameAndStatus(merchantName, "申请中");

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();

            // 转换订单列表为JSON
            StringBuilder json = new StringBuilder("[");
            for (int i = 0; i < orders.size(); i++) {
                UserHistoryOrdersPO order = orders.get(i);
                json.append("{")
                        .append("\"orderId\":").append(order.getOrderId()).append(",")
                        .append("\"userId\":").append(order.getUserId()).append(",")
                        .append("\"merchantName\":\"").append(escapeJson(order.getMerchantName())).append("\",")
                        .append("\"roomTypeName\":\"").append(escapeJson(order.getRoomTypeName())).append("\",")
                        .append("\"bedType\":\"").append(escapeJson(order.getBedType())).append("\",")
                        .append("\"roomTypeQuantity\":").append(order.getRoomTypeQuantity()).append(",")
                        .append("\"checkInTime\":").append(order.getCheckInTime().getTime()).append(",")
                        .append("\"checkOutTime\":").append(order.getCheckOutTime().getTime()).append(",")
                        .append("\"orderStatus\":\"").append(escapeJson(order.getOrderStatus())).append("\"")
                        .append("}");

                if (i < orders.size() - 1) {
                    json.append(",");
                }
            }
            json.append("]");

            out.print(json.toString());
            out.flush();

        } else if ("approve".equals(action)) {
            // 同意入住申请
            String orderIdStr = request.getParameter("orderId");
            String merchantName = request.getParameter("merchantName");

            if (orderIdStr == null || merchantName == null) {
                response.getWriter().println("参数缺失");
                return;
            }

            try {
                int orderId = Integer.parseInt(orderIdStr);

                // 获取订单信息
                UserHistoryOrdersPO order = dao.getOrderById(orderId);
                if (order == null) {
                    response.getWriter().println("订单不存在");
                    return;
                }

                // 检查订单状态
                if (!"申请中".equals(order.getOrderStatus())) {
                    response.getWriter().println("订单状态不是申请中，无法处理");
                    return;
                }

                // 更新订单状态为已入住
                order.setOrderStatus("已入住");
                order.setOrderPlacementTime(new Timestamp(System.currentTimeMillis())); // 更新处理时间

                boolean success = dao.updateOrder(order);
                if (success) {
                    response.getWriter().println("入住申请已批准");
                } else {
                    response.getWriter().println("批准入住失败，请重试");
                }

            } catch (NumberFormatException e) {
                response.getWriter().println("无效的订单ID");
                e.printStackTrace();
            }
        }
    }

    // 辅助方法：转义JSON字符串
    private String escapeJson(String s) {
        if (s == null) return "";
        return s.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
